var platformListData = [];
/**
 * 进入游戏
 * @param gameId 游戏ID
 * @param platFormCode 平台代码
 */
function playGame(gameId, platFormCode) {
	closelayer();
	if (!user) {
		popTips("用户未登录", 'waring');
		return;
	}
	var dataUrl = null;
	$.ajax({
		url: "/ct-data/baccarat/playGame",
		type: "post",
		dataType: "json",
		data: {
			"gameId": gameId
		},
		async: false,
		success: function(data) {
			if (data && data.sign) {
				dataUrl = data.dataUrl;
			} else {
				transferGame(platFormCode, true, gameId);
			}
		},
		error: function() {
			popTips("进入游戏失败", "error");
		}
	});
	if (dataUrl) {
		window.open(dataUrl);
	}
}

var openReturn = false;
/**
 * 开通平台
 */
function createBaccaratAccount() {
	closelayer();
	if (!user) {
		popTips("用户未登录", "waring");
		return;
	}
	popTips("正在开通... ...", 'waring');
	var platformCode = $("#createPlatformCode").val();
	var gameId;
	if($("#createGameId").length > 0) {
		gameId = $("#createGameId").val();
	}
	intoTransferGame(platformCode, gameId);
	$.ajax({
		url: '/ct-data/baccarat/createAccount',
		type: 'POST',
		dataType: 'json',
		data: {
			'platformCode': platformCode
		},
		success: function(data) {
			if (data.sign === true) {
				openReturn = true;
			} else {
				popTips(data.message, 'error');
			}
		},
		error: function(xhr, textStatus, errorThrown) {
			//called when there is an error
		}
	});
}

var intoTransferGameIndex;
function intoTransferGame(platformCode, gameId) {
	clearTimeout(intoTransferGameIndex);
	if (openReturn === false) {
		intoTransferGameIndex = setTimeout(function() {
			intoTransferGame(platformCode, gameId);
		}, 100);
		return;
	}
	if (openReturn === true) {
		closeSystemLayer();
        if($("#intoPlatformTips").length>0){
            pop("intoPlatformTips");
            if(gameId) {
                $("#intoPlatformButton").attr("onclick", "playGame('"+gameId+"', '"+platformCode+"');");
            } else {
                $("#intoPlatformButton").attr("onclick", "transferGame('" + platformCode + "');");
            }
        }else{
            <!-- 开通平台成功 ，是否进入游戏提示框 -->
            var html =' <div id="intoPlatformTips" class="aar a-one" style="display:none;"><div class="aar-center">';
            html+='<div class="aar-title">温馨提示</div><a class="aar-close" onclick="closelayer();"><i class="demo-icon icon-ios-close-empty member-close"></i></a> <div class="tishik">'
            html+='<div class="bd"><div class="bd text-center"><div class="pop-title"><i class="ico-succeed"></i>';
            html+='<h4 class="pop-text">开通成功，是否进入游戏？</h4></div></div></div> </div>'
            if(gameId){
                html+=' <div class="aar-but"> <a class="confirm" id="intoPlatformButton" href="javascript:;" onclick="playGame(\''+gameId+'\',\''+platformCode+'\');">是</a>&nbsp;&nbsp;';
            }else{
                html+=' <div class="aar-but"> <a class="confirm" id="intoPlatformButton" href="javascript:;" onclick="transferGame(\''+platformCode+'\');">是</a>&nbsp;&nbsp;';
            }
            html+='<a class="confirm" href="javascript:;" onclick="closelayer();">否</a></div></div></div>'
            $('body').append(html);

            pop("intoPlatformTips");
        }
	}
	openReturn = false;
}

// 新窗口打开链接
function openwin(url) {
	var a = document.createElement("a");
	a.setAttribute("href", url);
	a.setAttribute("target", "_blank");
	document.body.appendChild(a);
	a.click();
}
/**
 * 获取百家乐平台与用户是否开通信息
 * @param isHaveMoney
 */
var platformList = function() {
    jQuery.ajax({
        url: '/ct-data/baccarat/platformList',
        async:false,
        type: 'POST',
        dataType: 'json',
        cache:false,//设置不缓存
        success: function (data, textStatus, xhr) {
            if (data.sign) {
                platformListData = data.list
                $.each(data.list, function (index, val) {
                    var html = '';
                    $('#' + val.value).find('a').remove();
                    if (val.isOpenSys) {
                        if (val.isOpen) {
                            if (val.code == '0011') {
                                html += '<a href="http://www.yule1688.com/download/twinkleray.msi" target="_blank">下载游戏</a>';
                                html += '<a href="javascript:transferGame(\'' + val.code + '\');">我的棋牌</a>';
                            } else {
                                // PT MG KBET
                                if (val.code == '0002') { // pt
                                    html += '<a href="javascript:playGame(\'B15875EFD3804D7BACACBB50318902EC\',\'' + val.code + '\');">进入游戏</a>';
                                } else if (val.code == '0006') { // mg
                                    html += '<a href="javascript:playGame(\'0D1CF5E0F27B4C4FBE6A2D0C187CE641\',\'' + val.code + '\');">进入游戏</a>';
                                } else if (val.code == '0007') { // kbet
                                    html += '<a href="javascript:playGame(\'A31DB032-D9E5-4F3B-A492-CD76EA1C4BF0\',\'' + val.code + '\');">进入游戏</a>';
                                } else {
                                    html += '<a href="javascript:transferGame(\'' + val.code + '\');">进入游戏</a>';
                                }
                            }
							html += '<a href="javascript:;">  转出</a>';
                            html+='<a><strong class="haveMoney"></strong><i  class="l_refersh" onclick="dsPlatFormList(\''+val.code+'\',this)"></i></a></span>';
                        } else {
                            html += '<a id="' + val.code + '" href="javascript:;" onclick="transferGame(\'' + val.code + '\',true)"><strong>开通</strong></a>';
                        }
                    } else {
                        html += '<a href="javascript:;"><strong>系统未开通</strong></a>';
                    }
                    $('#' + val.value).append(html);
                });
            } else {
                popTips(data.message, 'error');
            }
            // 获取账户可用额
            initTotalBalance();
        },
        error: function(xhr, textStatus, errorThrown) {}
    });
};

/**
 * 打开平台
 * 
 * @param platFormCode 平台代码
 * @param haveOpenTips 是否弹出开通提示
 * @param gameId 游戏ID
 */
function transferGame(platFormCode, haveOpenTips, gameId) {
	closelayer();
	if(platformListData.length<=0){
        platformList();
	}
	if (!user) {
		popTips("用户未登录", 'waring');
		return;
	}
	$.ajax({
		url: "/ct-data/baccarat/transferGame",
		type: "post",
		dataType: "json",
		async: false,
		data: {
			"platFormCode": platFormCode
		},
		success: function(data) {
			if (data && data.sign === true) {
				openwin(data.dataUrl);
			} else {
				if (data.isOpen === false && haveOpenTips) {
                    if(gameId) {
                        if($("#createGameId").length>0){
                            $("#createGameId").val(gameId);
                        }else{
                            $('body').append('<input type="hidden" id="createGameId" value="'+gameId+'">');
                        }

                    }
                    if($("#openPlatformTips").length>0){
                        $("#baccact_pswd").val('');
						$("#baccact_repswd").val('');
                        $("#createPlatformCode").val(platFormCode);
                        for(var k=0;k<platformListData.length;k++){
                            if(platformListData[k].code == platFormCode){
                                if(platformListData[k].isOpenPassword){
                                    $(".isShowBaccact").show();
                                }else{
                                    $(".isShowBaccact").hide();
                                }
                            }
                        }
                        pop("openPlatformTips");
                    }else{

						// <!-- 开通平台提示框 -->
						var html = '<div id="openPlatformTips" class="aar a-one" style="display:none;">';
						html+='<div class="aar-center"><div class="aar-title">温馨提示</div><a class="aar-close" onclick="closelayer();"><i class="demo-icon icon-ios-close-empty member-close"></i></a>';
						html+='<div class="tishik"><div class="bd"> <div class="bd text-center"><div class="pop-title"> <i class="ico-waring"></i>';
						html+='<input type="hidden" id="createPlatformCode" value="'+platFormCode+'"> <h4 class="pop-text">您还未开通此平台，是否开通？</h4>';
						html+='<dl class="isShowBaccact password" style="display: none"> <dd> <span class="tt">密码：</span>'
						html+='<span><input  id="baccact_pswd" type="password"></span></dd>'
						html+='<dd><span class="tt">确认密码：</span><span><input  id="baccact_repswd"  type="password"></span></dd></dl>'

						html+='</div></div></div></div><div class="aar-but"><a class="confirm" href="javascript:;" onclick="openBaccaratAccount();">是</a>&nbsp;&nbsp;';
						html+='<a class="confirm" href="javascript:;" onclick="closelayer();">否</a></div> </div></div>';
						$('body').append(html);
                        for(var k=0;k<platformListData.length;k++){
                            if(platformListData[k].code == platFormCode){
                                if(platformListData[k].isOpenPassword){
                                	$(".isShowBaccact").show();
                                }else{
                                    $(".isShowBaccact").hide();
								}
							}
						}
                        pop("openPlatformTips");
                    }
				} else {
					popTips(data.message, 'error');
				}
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			popTips("进入游戏失败", "error");
		}
	});
}

/**
 * 开通平台
 * @param platformCode 平台代码
 */
function openBaccaratAccount(platformCode, e, isQueryGame) {
    platformCode = $("#createPlatformCode") .val().trim();
    if (!user) {
        popTips("用户未登录", "waring");
        return false;
    }

    var pswd, repswd;
	if(!$('.isShowBaccact').is(":hidden")) {
		 pswd = $("#baccact_pswd").val();
		 repswd = $("#baccact_repswd").val();
		 if(!pswd) {
			 popTips("请输入新密码", "waring");
			 return false;
		 }
		 if(pswd.length<6 || pswd.length>12) {
			 popTips("密码长度6-12位字符", "waring");
			 return false;
		 }
		 if(!repswd) {
			 popTips("请输入确认密码", "waring");
			 return false;
		 }
		 if(pswd != repswd) {
			 popTips("确认密码与新密码不一致", "waring");
			 return false;
		 }
	 }

    $("#" + platformCode).attr("onclick", "");
    $("#" + platformCode).find('strong').text("正在开通...");

    if(e) {
        $(e.target).removeAttr("onclick");
        $(e.target).text("正在开通...");
    }

    jQuery.ajax({
        url: '/ct-data/baccarat/createAccount',
        type: 'POST',
        dataType: 'json',
        data: {
            "platformCode": platformCode,
            "pswd" : pswd,
            "repswd" : repswd
        },
        success: function (data) {
            if (data.sign === true) {
                var html = '';
                if (platformCode == '0011') {
                    html += '<a href="http://www.yule1688.com/download/twinkleray.msi" target="_blank">下载游戏</a>';
                    html += '<a href="javascript:transferGame(\'' + platformCode + '\');">我的棋牌</a>';
                    //html += '<a id="' + platformCode + '" href="javascript:;" onclick="updateChessPwdTips(false);">改密码</a>';
                } else {
                    // html += '<a href="javascript:transferGame(\'' + platformCode + '\');">进入游戏</a>';
                    // PT MG KBET
                    if (platformCode == '0002') { // pt
                        html += '<a href="javascript:playGame(\'B15875EFD3804D7BACACBB50318902EC\',\'' + platformCode + '\');">进入游戏</a>';
                    } else if (platformCode == '0006') { // mg
                        html += '<a href="javascript:playGame(\'0D1CF5E0F27B4C4FBE6A2D0C187CE641\',\'' + platformCode + '\');">进入游戏</a>';
                    } else if (platformCode == '0007') { // kbet
                        html += '<a href="javascript:playGame(\'A31DB032-D9E5-4F3B-A492-CD76EA1C4BF0\',\'' + platformCode + '\');">进入游戏</a>';
                    } else {
                        html += '<a href="javascript:transferGame(\'' + platformCode + '\');">进入游戏</a>';
                    }
                }
                html += '<a href="javascript:;">转出</a>';
                html+='<a><strong class="haveMoney"></strong><i  class="l_refersh" onclick="dsPlatFormList(\''+ platformCode +'\',this)"></i></a>';
                var parentTab = $("#" + platformCode);
                if (parentTab.length > 0) {
                    parentTab = parentTab.parent('li');
                    $("#" + platformCode).remove();
                    parentTab.append(html);
                }
                if (isQueryGame) {
                    queryGame();
                }
                popTips(data.message, 'succeed',"",function(){
                    platformList();
                });
            } else {
                $("#" + platformCode).find('strong').text("开通");
                popTips(data.message, 'error');
            }
        },
        error: function(xhr, textStatus, errorThrown) {
            //called when there is an error
        },
        complete: function() {
            closelayer();
            if(e) {
                $("#" + platformCode).attr('onclick', 'updateChessPwdTips(true);');
                $(e.target).attr("onclick", "transferGame(\'"+platformCode+"\', event, true);");
                $(e.target).text("确定");
            } else {
                $("#" + platformCode).attr('onclick', 'transferGame(\'' + platformCode + '\', true)');
            }
        }
    });
}

// 生成对应的彩种的走势链接
var getLotteryLink = function () {
    var searchStr = window.location.search;
    var lotteryCode = getQueryString(searchStr.substr(1), "code");
    if (lotteryCode) {
        $("#btnTrend").attr("href", "trendChart.html?code=" + lotteryCode);
    }
}


/**
 * 进入时时彩
 * @param lotteryCode 时时彩代码
 */
function transferLottery(lotteryCode) {
	if (!user) {
		popTips("用户未登录", "waring");
		return;
	}
	window.location.href = currentRootDirectory + '/view/game/game.html?code=' + lotteryCode;
}

/**
 * 进入快乐彩任选
 * @param shortName 快乐彩代码
 */
function transferKlcrx(shortName) {
	if (!user) {
		popTips("用户未登录", "waring");
		return;
	}
	window.location.href = currentRootDirectory + '/view/game/game-klc-rx.html?code=' + shortName;
}

/**
 * 开通棋牌游戏，或更改棋牌游戏密码
 * @param isOpen
 */
function updateChessPwdTips(isOpen, isQueryGame) {
	if (!user) {
		popTips("用户未登录", 'waring');
		return;
	}
	if(isOpen == true) {
		$("#updataChessPwdTips .aar-title").text("开通棋牌游戏");
		$("#updataChessPwdTips .validate-form dt").show();
		$("#updataChessPwdTips .validate-form dd:first").hide();
		
		$("#updataChessPwdTips .aar-but a").attr("onclick", "openBaccaratAccount('0011', event, "+isQueryGame+");");
	} else {
		$("#updataChessPwdTips .aar-title").text("修改游戏登录密码");
		$("#updataChessPwdTips .validate-form dt").hide();
		$("#updataChessPwdTips .validate-form dd:first").show();
		
		$("#updataChessPwdTips .aar-but a").attr("onclick", "updataChessPwd('0011');");
	}
	
	pop("updataChessPwdTips");
}

function updataChessPwd(platformCode) {
	var oldpswd = $("#updataChessPwdTips .validate-form .inp-sty-1:eq(0)").val().trim();
	var pswd = $("#updataChessPwdTips .validate-form .inp-sty-1:eq(1)").val().trim();
	var repswd = $("#updataChessPwdTips .validate-form .inp-sty-1:eq(2)").val().trim();
	
	if(!oldpswd) {
		popTips("请输入旧密码", "waring");
		return;
	}
	if(oldpswd.length<6 || oldpswd.length>12) {
		popTips("旧密码长度6-12位字符", "waring");
		return;
	}
	if(!pswd) {
		popTips("请输入新密码", "waring");
		return;
	}
	if(pswd.length<6 || oldpswd.length>12) {
		popTips("新密码长度6-12位字符", "waring");
		return;
	}
	if(!repswd) {
		popTips("请输入确认密码", "waring");
		return;
	}
	if(pswd != repswd) {
		popTips("确认密码与新密码不一致", "waring");
		return;
	}
	
	closelayer();
	
	$.ajax({
		url: "/ct-data/baccarat/changePwd",
		type: "post",
		dataType: "json",
		data: {
			"platformCode": platformCode,
			"oldpswd": oldpswd,
			"pswd" : pswd,
			"repswd" : repswd
		},
		success: function(data) {
			if (data && data.sign === true) {
				popTips(data.message, "succeed");
			} else {
				popTips(data.message, "error");
			}
		}
	});
}


/**
 * 获取账户总额
 */
var initTotalBalance = function(){
	if(!way.get("useraccount.balance")){
		setTimeout(function(){
			initTotalBalance();},100);
		return ;
	}
	way.set("totalBalance", (parseFloat(way.get("useraccount.balance")) + parseFloat(way.get("useraccount.commission"))).toFixed(4));
};

/**
 * 获取百家乐平台单平台账户刷新金额
 * @param isHaveMoney
 */

function  dsPlatFormList(platformCode,dom) {
    $(dom).removeClass("cur-refresh");
    jQuery.ajax({
        url: '/ct-data/baccarat/getAccountMoeny',
        type: 'POST',
        dataType: 'json',
        data: {"platformCode": platformCode},
        success: function (data, textStatus, xhr) {
            if (data.sign) {
                $(dom).addClass("cur-refresh");
                var balance = data.balance;
                $(dom).parent().find('strong').text(balance + '元');
            }
        }
    })
}
